package com.test40_JDBC.service.impl;

import com.test40_JDBC.service.IBatchService;
import com.test40_JDBC.util.JDBCUtil;
import com.test40_JDBC.vo.Dept;
import com.test40_JDBC.vo.Emp;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

public class BatchServiceImpl implements IBatchService {
    private Connection connection;
    private PreparedStatement deptPstmt;
    private PreparedStatement empPstmt;

    public BatchServiceImpl() {
        try {
            this.connection = JDBCUtil.getConnection();
            this.connection.setAutoCommit(false);   // 取消自动提交
        } catch (Exception e) {
            System.out.println("【错误】数据库无法使用，程序无法正常执行！");
            System.exit(1);     // 退出程序
        }
    }

    @Override
    public void deptBatch(List<Dept> depts) throws SQLException {
        String sql = "INSERT INTO dept (deptno, dname, loc) VALUES (?, ?, ?)";
        this.deptPstmt = this.connection.prepareStatement(sql);
        for (Dept dept : depts) {
            this.deptPstmt.setObject(1, dept.getDeptno());
            this.deptPstmt.setObject(2, dept.getDname());
            this.deptPstmt.setObject(3, dept.getLoc());
            this.deptPstmt.addBatch();  // 添加到批处理
        }
    }

    @Override
    public void empBatch(List<Dept> depts) throws SQLException {
        String sql = "INSERT INTO emp (ename, salary, deptno) VALUES (?, ?, ?)";
        this.empPstmt = this.connection.prepareStatement(sql);
        for (Dept dept : depts) {
            for (Emp emp : dept.getEmps()) {
                this.empPstmt.setObject(1, emp.getEname());
                this.empPstmt.setObject(2, emp.getSalary());
                this.empPstmt.setObject(3, emp.getDept().getDeptno());
                this.empPstmt.addBatch();
            }
        }
    }

    @Override
    public void rollback() throws SQLException {
        this.connection.rollback();
    }

    @Override
    public void commit() throws SQLException {
        this.deptPstmt.executeBatch();  // 执行批处理
        this.empPstmt.executeBatch();
        this.connection.commit();
    }

    @Override
    public void close() throws Exception {
        this.connection.close();
    }
}
